package cn.wolfcode.shop.cloud.filter;

import cn.wolfcode.shop.cloud.common.CookieUtils;
import cn.wolfcode.shop.cloud.common.Result;
import cn.wolfcode.shop.cloud.feign.UserFeignApi;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.sun.deploy.net.cookie.CookieUnavailableException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by wolfcode-lanxw
 */
@Component
public class TokenRefreshFilter extends ZuulFilter {

    @Autowired
    private UserFeignApi userFeignApi;

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        // 如果取到token才进行过滤
        return !StringUtils.isEmpty(CookieUtils.getToken(request));
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = CookieUtils.getToken(request);
        // 1.更新redis中的token
        Result<Boolean> result = userFeignApi.refreshToken(token);
        if (result.hasError()) {
            return null;
        }

        Boolean expired = result.getData();
        // 2. 更新 cookie 中的token
        if (expired) {
            CookieUtils.addToken(token, ctx.getResponse());
        }
        return null;
    }
}
